package me.magicall.myblog.admin.web.springmvc.controllers;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import me.magicall.db.meta.DbColumn;
import me.magicall.db.meta.TableMeta;
import me.magicall.db.meta.TableMetaAccessor;
import me.magicall.db.model.BaseModel.NbBean;
import me.magicall.db.model.BaseModel.NbBean.NbBeanLong;
import me.magicall.db.util.DbUtil;
import me.magicall.myblog.util.DaoFactory;
import me.magicall.myblog.util.UrlPatternRule;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

@RequestMapping(method = RequestMethod.POST, //
value = { /* "/admin" + */UrlPatternRule.MODEL_NAME + "/update",//
})
@Controller("updateController")
public class UpdateController {

	@Autowired
	private TableMetaAccessor tableMetaBuilder;
	@Autowired
	private DaoFactory daoFactory;

	//add
	@RequestMapping( { "", "/" })
	public String update(final HttpServletRequest request, final ModelMap modelMap,//
			@PathVariable("modelName") final String modelName) {
		update(request, modelMap, modelName, 0);
		return UrlBasedViewResolver.REDIRECT_URL_PREFIX + "/" + modelName;
	}

	@RequestMapping(UrlPatternRule.ID)
	public String update(final HttpServletRequest request, final ModelMap modelMap,//
			@PathVariable("modelName") final String modelName,//
			@PathVariable("id") final long id) {
		final NbBean<?> nbBean = new NbBeanLong();
		if (id != 0) {
			nbBean.set(DbUtil.COMMON_ID_FIELD_NAME, id);
			modelMap.addAttribute("id", id);
		}

		final TableMeta tableMeta = tableMetaBuilder.getTableMetaUsingModelName(modelName);
		final List<DbColumn> columns = tableMeta.getColumns();
		for (final DbColumn c : columns) {
			final String fieldName = DbUtil.dbNameToJavaName(c.getName());
			final String[] parameterValues = request.getParameterValues(fieldName);
			if (parameterValues != null) {
				if (parameterValues.length == 0) {
					nbBean.set(fieldName, true);//没有值的当做bool处理
				} else {
					final String parameterValue = parameterValues[0];
					nbBean.set(fieldName, parameterValue);
				}
			}
		}

		daoFactory.getNbBeanDao(modelName).addOrUpdate(nbBean);

		modelMap.addAttribute("modelName", modelName);
		return UrlBasedViewResolver.REDIRECT_URL_PREFIX + "/" + modelName + "/" + id;
	}
}
